package com.veeder.datacollection.rs232.comm;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.logging.Level;

import com.veeder.datacollection.util.GlobalConstants;

public class TCPConnection extends Connection {

	private InetSocketAddress serverSocketAddr;
	private Socket socket;
	private Object socketLockObject = new Object();

	public TCPConnection(InetSocketAddress socketAddress, int connectionTimeout, int readTimeout) {
		super(connectionTimeout, readTimeout);
		this.serverSocketAddr = socketAddress;
	}

	public InetSocketAddress getServerSocketAddr() {
		return serverSocketAddr;
	}

	public void setServerSocketAddr(InetSocketAddress serverSocketAddr) {
		this.serverSocketAddr = serverSocketAddr;
	}

	public void openConnection() throws IOException {
		logger.log(Level.INFO, "open connection...");

		logger.log(Level.INFO, "connecting to " + serverSocketAddr.toString());
		synchronized (socketLockObject) {
			socket = new Socket();
			socket.setSoTimeout(getReadTimeout()*GlobalConstants.MILLISECONDS_PER_SECOND);
			socket.connect(serverSocketAddr, getConnectionTimeout()*GlobalConstants.MILLISECONDS_PER_SECOND);
			in = new BufferedInputStream(socket.getInputStream());
			out = new BufferedOutputStream(socket.getOutputStream());
		}
		logger.log(Level.INFO, "connected to " + serverSocketAddr.toString());
	}

	public void closeConnection() {
		logger.log(Level.INFO, "close connection...");
		synchronized (socketLockObject) {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					logger.log(Level.WARNING, "encounter " + e.toString() + " when close connection...");
				}
			}
		}
	}

   public int read(byte[] b) throws IOException
   {
      int len = -1;
      synchronized (socketLockObject)
      {  
         len = in.read(b); 
      }
      return len;
   }

	public synchronized boolean isValid() {
		return socket != null && socket.isConnected() && !socket.isClosed();
	}

}
